package com.zhenwei.zscm.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zhenwei.zscm.common.base.UserContext;
import com.zhenwei.zscm.model.dto.user.UserDTO;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        UserDTO currentUser = UserContext.getCurrentUser();

        var now = new Date();
        Object cTime = metaObject.getValue("cTime");
        Object cUserId = metaObject.getValue("cUserId");
        Object cUser = metaObject.getValue("cUser");
        if(cUserId == null){
            this.strictInsertFill(metaObject, "cUserId", String.class, currentUser.getGuid());
        }
        if(cUser == null){
            this.strictInsertFill(metaObject, "cUser", String.class, currentUser.getRealName());
        }
        if(cTime == null){
            this.strictInsertFill(metaObject, "cTime", Date.class,  now);
        }
        this.strictInsertFill(metaObject, "uUserId", String.class, currentUser.getGuid());
        this.strictInsertFill(metaObject, "uUser", String.class, currentUser.getRealName());
        this.strictInsertFill(metaObject, "uTime", Date.class, now);
        this.strictInsertFill(metaObject, "deleted", Boolean.class, false);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserDTO currentUser = UserContext.getCurrentUser();
        this.strictInsertFill(metaObject, "uUserId", String.class, currentUser.getGuid());
        this.strictInsertFill(metaObject, "uUser", String.class, currentUser.getRealName());
        this.strictUpdateFill(metaObject, "uTime", Date.class, new Date());
    }
}
